package hidalgo.expenses.activity;

import hidalgo.expenses.R;
import hidalgo.expenses.SessionManager;
import hidalgo.expenses.adapter.NoteViewAdapter;
import hidalgo.expenses.dao.NoteDao;
import hidalgo.expenses.entities.Note;
import hidalgo.expenses.utils.Constants;
import hidalgo.expenses.utils.HideAnimation;
import hidalgo.expenses.utils.Properties;
import hidalgo.expenses.widgets.ActionBar;

import java.util.ArrayList;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class QuickNoteActivity extends BaseActivity {

	private Button btnTakePic;
	private Button btnTextNote;
	private Button btnGallery;

	private ListView noteListView;

	private ActionBar actionBar;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.quick_note_activity);

		btnTakePic = (Button) findViewById(R.id.btnTakePic);
		btnGallery = (Button) findViewById(R.id.btnGallery);
		btnTextNote = (Button) findViewById(R.id.btnTextNote);
		noteListView = (ListView) findViewById(R.id.noteList);

		setUpActionBar();

		populateNotes();

		btnTakePic.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {

			}
		});

		btnGallery.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

			}
		});

		btnTextNote.setOnClickListener(new OnClickListener() {

			public void onClick(View view) {

				Intent intent = new Intent(QuickNoteActivity.this,
						NoteEditor.class);
				startActivityForResult(intent, Constants.REQ_CODE_NOTE);

			}
		});

		registerForContextMenu(noteListView);

		noteListView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View view, int pos,
					long id) {
				noteListView.showContextMenu();
			}
		});

		noteListView.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				return false;
			}
		});

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		
		
		if (requestCode == Constants.REQ_CODE_NOTE)
	     {
	         if (resultCode == RESULT_OK)
	         {
	        	 Bundle extras = intent.getExtras();
	        	 if (extras != null) {
	     			boolean isEditMode = extras.getBoolean(Constants.NOTE_EDITOR_ISEDITMODE);
	     			if (isEditMode) {
	     				Note note = (Note) extras.getSerializable(Constants.NOTE_OBJECT);
	     				
	     				Log.d("aaaaaaaaaaaaaaaa","bbbbbbb");
	     				
	     				((NoteViewAdapter)noteListView.getAdapter()).updateNote(note);
						((NoteViewAdapter)noteListView.getAdapter()).notifyDataSetChanged();
	     			}
	     		}
	        	 
	         }
	     }
		
		
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

		int id = (int) noteListView.getAdapter().getItemId(info.position);

		menu.setHeaderTitle("Desea...");
		menu.add(0, id, 0, "Editar");
		menu.add(0, id, 0, "Eliminar");

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getTitle() == "Eliminar") {
			deleteNote(item.getItemId());
		} else if (item.getTitle() == "Editar") {

			editNote(item.getItemId());

		} else {
			return false;
		}

		return super.onContextItemSelected(item);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		unregisterForContextMenu(noteListView);
	}

	private void editNote(int noteId) {

		// open note editor in edit mode.
		Intent intent = new Intent(QuickNoteActivity.this, NoteEditor.class);
		intent.putExtra(Constants.NOTE_EDITOR_ISEDITMODE, true);
		intent.putExtra("NOTEID", noteId);
		startActivityForResult(intent, Constants.REQ_CODE_NOTE);

	}

	private void setUpActionBar() {

		actionBar = (ActionBar) findViewById(R.id.actionBar);
		actionBar.setTitle("Notas");
		// set home icon that does nothing when the user clicks on it
		actionBar.setHomeLogo(R.drawable.ic_title_home_default,
				new OnClickListener() {
					public void onClick(View v) {
						QuickNoteActivity.this.finish();
					}
				});
	}

	private void deleteNote(final int id) {
		new AsyncTask<Integer, Integer, Boolean>() {

			@Override
			protected Boolean doInBackground(Integer... params) {

				return NoteDao.deleteNoteById((int) params[0]);
			}

			protected void onPostExecute(Boolean success) {

				if (success) {
					Toast.makeText(QuickNoteActivity.this,
							"Eliminado correctamente", Toast.LENGTH_SHORT)
							.show();
					((NoteViewAdapter)noteListView.getAdapter()).removeNote(id);
					((NoteViewAdapter)noteListView.getAdapter()).notifyDataSetChanged();
				} else {
					Toast.makeText(QuickNoteActivity.this, "Error al eliminar",
							Toast.LENGTH_SHORT).show();
				}

			};

		}.execute(id);
	}

	public void populateNotes() {

		new AsyncTask<Integer, Integer, ArrayList<Note>>() {

			protected void onPreExecute() {

				actionBar.showProgressBar();
				actionBar.getProgressBar().startLoading(
						Properties.progressBarSpeed);
			};

			@Override
			protected ArrayList<Note> doInBackground(Integer... params) {

				int userId = params[0];

				return NoteDao.getNotesByUser(userId);
			}

			protected void onPostExecute(ArrayList<Note> noteList) {

				if (noteList != null) {

					NoteViewAdapter noteAdapter = new NoteViewAdapter(
							QuickNoteActivity.this, R.layout.note_item,
							noteList);

					noteListView.setAdapter(noteAdapter);

				}

				actionBar.getProgressBar().completeLoading();
				actionBar.getProgressBar().startAnimation(
						new HideAnimation(1.0f, 1.0f, 1.0f, 0.0f, 500,
								actionBar.getProgressBar(), true));

			};

		}.execute(SessionManager.userId);

	}
}
